--CREATE FOREIGN KEY BETWEEN DIFFERENT TABLE

--CREATE FOREIGN KEY FK_DATCHO_KHACHHANG

IF EXISTS(SELECT * FROM SYS.FOREIGN_KEYS WHERE NAME='FK_DATCHO_KHACHHANG')
BEGIN
	ALTER TABLE DATCHO
	DROP CONSTRAINT FK_DATCHO_KHACHHANG
END
GO
ALTER TABLE DATCHO
ADD CONSTRAINT FK_DATCHO_KHACHHANG
FOREIGN KEY(MAKH)
REFERENCES KHACHHANG(MAKH)

--CREATE FOREIGN KEY FK_DATCHO_LICHBAY_1

IF EXISTS(SELECT * FROM SYS.FOREIGN_KEYS WHERE NAME='FK_DATCHO_LICHBAY')
BEGIN
	ALTER TABLE DATCHO
	DROP CONSTRAINT FK_DATCHO_LICHBAY
END
GO
ALTER TABLE DATCHO
ADD CONSTRAINT FK_DATCHO_LICHBAY
FOREIGN KEY(NGAYDI,MACB)
REFERENCES LICHBAY(NGAYDI,MACB)

--CREATE FOREIGN KEY FK_LICHBAY_CHUYENBAY

IF EXISTS(SELECT * FROM SYS.FOREIGN_KEYS WHERE NAME='FK_LICHBAY_CHUYENBAY')
BEGIN
	ALTER TABLE LICHBAY
	DROP CONSTRAINT FK_LICHBAY_CHUYENBAY
END
GO
ALTER TABLE LICHBAY
ADD CONSTRAINT FK_LICHBAY_CHUYENBAY
FOREIGN KEY(MACB)
REFERENCES CHUYENBAY(MACB)

--CREATE FOREIGN KEY FK_LICHBAY_MAYBAY

IF EXISTS(SELECT * FROM SYS.FOREIGN_KEYS WHERE NAME='FK_LICHBAY_MAYBAY')
BEGIN
	ALTER TABLE LICHBAY
	DROP CONSTRAINT FK_LICHBAY_MAYBAY
END
GO
ALTER TABLE LICHBAY
ADD CONSTRAINT FK_LICHBAY_MAYBAY
FOREIGN KEY(SOHIEU,MALOAI)
REFERENCES MAYBAY(SOHIEU,MALOAI)

--CREATE FOREIGN KEY FK_MAYBAY_LOAIMB

IF EXISTS(SELECT * FROM SYS.FOREIGN_KEYS WHERE NAME='FK_MAYBAY_LOAIMB')
BEGIN
	ALTER TABLE MAYBAY
	DROP CONSTRAINT FK_MAYBAY_LOAIMB
END
GO
ALTER TABLE MAYBAY
ADD CONSTRAINT FK_MAYBAY_LOAIMB
FOREIGN KEY(MALOAI)
REFERENCES LOAIMB(MALOAI)

--CREATE FOREIGN KEY FK_KHANANG_LOAIMB

IF EXISTS(SELECT * FROM SYS.FOREIGN_KEYS WHERE NAME='FK_KHANANG_LOAIMB')
BEGIN
	ALTER TABLE KHANANG
	DROP CONSTRAINT FK_KHANANG_LOAIMB
END
GO
ALTER TABLE KHANANG
ADD CONSTRAINT FK_KHANANG_LOAIMB
FOREIGN KEY(MALOAI)
REFERENCES LOAIMB(MALOAI)

--CREATE FOREIGN KEY FK_KHANANG_NHANVIEN

IF EXISTS(SELECT * FROM SYS.FOREIGN_KEYS WHERE NAME='FK_KHANANG_NHANVIEN')
BEGIN
	ALTER TABLE KHANANG
	DROP CONSTRAINT FK_KHANANG_NHANVIEN
END
GO
ALTER TABLE KHANANG
ADD CONSTRAINT FK_KHANANG_NHANVIEN
FOREIGN KEY(MANV)
REFERENCES NHANVIEN(MANV)

--CREATE FOREIGN KEY FK_PHANCONG_NHANVIEN

IF EXISTS(SELECT * FROM SYS.FOREIGN_KEYS WHERE NAME='FK_PHANCONG_NHANVIEN')
BEGIN
	ALTER TABLE PHANCONG
	DROP CONSTRAINT FK_PHANCONG_NHANVIEN
END
GO
ALTER TABLE PHANCONG
ADD CONSTRAINT FK_PHANCONG_NHANVIEN
FOREIGN KEY(MANV)
REFERENCES NHANVIEN(MANV)

--CREATE FOREIGN KEY FK_PHANCONG_LICHBAY

IF EXISTS(SELECT * FROM SYS.FOREIGN_KEYS WHERE NAME='FK_PHANCONG_LICHBAY')
BEGIN
	ALTER TABLE PHANCONG
	DROP CONSTRAINT FK_PHANCONG_LICHBAY
END
GO
ALTER TABLE PHANCONG
ADD CONSTRAINT FK_PHANCONG_LICHBAY
FOREIGN KEY(NGAYDI,MACB)
REFERENCES LICHBAY(NGAYDI,MACB)
